//
//  CompanyListViewController.m
//  ShangPiBao
//
//  Created by chirui on 2017/10/16.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "CompanyListViewController.h"
#import "CompanyListTableViewCell.h"
#import "CompanyMainDetailsVController.h"

@interface CompanyListViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>{
    
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    
    NSDictionary * dataDic;
}


@end

@implementation CompanyListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _page = 1;
    if (self.searchStr.length<=0) {
        
        self.searchStr= @"";
    }
    _dataArray = @[].mutableCopy;
    TitleView(self.titleStr);
    self.view.backgroundColor =[UIColor whiteColor];
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_return"  target:self action:@selector(backClick)];
    
    [self creatTableView];
    [self getDataForRequest];
    [self getBannerDataListRequest];
}

-(void)backClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)creatTableView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-48) style:UITableViewStyleGrouped];
    _tableView.dataSource =self;
    _tableView.delegate =self;
    _tableView.backgroundColor =[UIColor whiteColor];
   [_tableView registerNib:[UINib nibWithNibName:[CompanyListTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[CompanyListTableViewCell reuseIdentifier]];
    
    [self.view addSubview:_tableView];
    
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page =1;
        [self getDataForRequest];
        
    }];
    _tableView.mj_header =header;
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getDataForRequest];
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    _tableView.mj_footer.hidden = YES;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 80;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 80;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    CompanyListTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[CompanyListTableViewCell reuseIdentifier] forIndexPath:indexPath];
    
    [cell.companyImage sd_setImageWithURL:ImageUrl(dic[@"uca"]) placeholderImage:ImageName(@"img_company_head")];
    cell.compamyName.text = dic[@"ucn"];
    cell.detailsLabel.text = dic[@"uor"];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
    company.companyId = dic[@"uid"];
    company.companyNameStr = dic[@"ucn"];
    [self.navigationController pushViewController:company animated:YES];

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView * heardView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 80)];
    heardView.backgroundColor =[UIColor whiteColor];
    
    NSMutableArray * bannerImageArray = @[].mutableCopy;
    NSMutableArray * bannerIdArray = @[].mutableCopy;
    
    if ([dataDic[@"position1"] isKindOfClass:[NSArray class]]) {
        
        if (bannerImageArray.count>0) {
            
            [bannerIdArray removeAllObjects];
            [bannerImageArray removeAllObjects];
        }
        NSArray * arry = dataDic[@"position1"];
        for (NSDictionary * dic in arry) {
            
            [bannerImageArray addObject:dic[@"apicture"]];
            [bannerIdArray addObject:dic];
        }
    }
    
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0, WIDTH, 80) delegate:self placeholderImage:[UIImage imageNamed:@""]];
    cycleScrollView.backgroundColor =Color(229, 229, 229);
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    [heardView addSubview:cycleScrollView];
    cycleScrollView.autoScrollTimeInterval = 3.5;
    cycleScrollView.imageURLStringsGroup = bannerImageArray;
    if (bannerImageArray.count==1) {
        cycleScrollView.autoScroll = NO;
    }
    cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
        NSDictionary * dic = bannerIdArray[index];
        if ([dic[@"aurl"] isEqualToString:@"0"]) {
            
        }else{
            CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
            company.companyId = dic[@"aurl"];
            company.companyNameStr = dic[@"atitle"];
            company.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:company animated:YES];
        }
    };

    return heardView;
}

-(void)getDataForRequest{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSString * parametersStr;
    
    if ([self.isSearch isEqualToString:@"search"]) {
        parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&ucarea=陕西省&pclass=%@&so=%@&page=%d",address_url,new_addSearch_api,USER_DEFAULTGet(@"phone"),md5ver,self.classId,self.searchStr,_page];
    }else {
        parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&ucarea=陕西省&pclass=%@&so=%@&page=%d",address_url,get_compangList_api,USER_DEFAULTGet(@"phone"),md5ver,self.classId,self.searchStr,_page];
    }
    
    NSString *encoded = [parametersStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"parametersStr = %@",parametersStr);
    //    SHuiMBhubNoTimeLoding;
    [PostNetWorking netWorkingStr:encoded  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            _totailPage = [responseObject[@"maxpage"] intValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"data"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"data"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"data"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"data"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{

                if (_dataArray.count>10) {

                     _tableView.mj_footer.hidden = NO;
                }else {
                    _tableView.mj_footer.hidden = YES;
                   
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });

        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_tableView.mj_header endRefreshing];
            [_tableView reloadData];
            
        });
        
        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}

-(void)getBannerDataListRequest{
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&aclass=%@&page=1",address_url,new_allNews_api,USER_DEFAULTGet(@"phone"),md5ver,self.bannerIdStr];
    
    [PostNetWorking netWorkingStr:parametersStr  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            dataDic = responseObject;
            
        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_tableView.mj_header endRefreshing];
            [_tableView reloadData];
            
        });
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
}


@end
